<template>
    <div>

        <div class="navbar">
            <a href="#">Blog</a>
            <router-link to="/create">添加</router-link>
            <a href="#" class="right">{{username}}</a>
        </div>
        <table>
            <tr>
                <th>ID</th>
                <th style="width: 400px">标题</th>
                <th>日期</th>
                <th>操作</th>
            </tr>
            <tr v-for="blog in blogs" :key="blog.id" >
                <td>{{ blog.id }}</td>
                <td> <router-link :to="{ name: 'BlogDetail', params: { id: blog.id } }">{{ blog.title }}</router-link></td>
                <td>{{ blog.createDate}}</td>
                <td><button @click="editPost(blog.id)" class="btn" style="width: 50px">编辑</button> | <button @click="deletePost(blog.id)" class="btn" style="width: 50px">删除</button></td>
            </tr>
        </table>
    </div>
</template>

<script>
import axios from "axios";

export default {
    data() {
        return {
            username: "",
            blogs: [],
        };
    },
    mounted() {
        if(localStorage.getItem('user')===null){
            this.$router.replace({ path: "/login" });
        }

        this.getBlogData();

    },
    methods: {
        getBlogData() {
            axios.get('/api/backend/posts')
                .then(response => {
                    this.blogs = response.data.data;
                    this.username = JSON.parse(localStorage.getItem('user')).username;

                })
                .catch(error => {
                    console.error(error);
                });
        },
        deletePost(id) {
            const r = confirm("确定要删除吗？");
            if (r==true){
                axios.delete(`/api/posts/${id}`)
                    .then(response => {

                        this.getBlogData();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            }
            else{
                return
            }
        },
        editPost(id) {
            this.$router.push({ path: `/edit/${id}` });
        }

    },
};
</script>

<style>
.navbar {
    overflow: hidden;
    background-color: gray;
}

.navbar a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.navbar a.right {
    float: right;
}


table {
    width: 80%;
    margin: 20px auto 0;
    border-collapse: collapse;
}

th,
td {
    border: 1px solid #dddddd;
    text-align: center;
    padding: 8px;
}

th:nth-child(1),
td:nth-child(1) {
    width: 8%;
}

th:nth-child(2),
td:nth-child(2) {
    width: 50%;
}

th:nth-child(3),
td:nth-child(3) {
    width: 20%;
}

th:nth-child(4),
td:nth-child(4) {
    width: 12%;
}
</style>




